//
//  FreebaseSuggest.m
//
//  Created by Alec Flett on 11/18/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "FreebaseSuggest.h"
#import "Freebase.h"
#import "JSON.h"
#import "FBTableViewCell.h"

#import <CoreLocation/CoreLocation.h>

@implementation FreebaseSuggest

@synthesize delegate = _delegate;
@synthesize search = _search;

@synthesize itemDetail = _itemDetail;
@synthesize itemDetailParentView = _itemDetailParentView;
@synthesize showDetail = _showDetail;
@dynamic allowCreateNew, allowGeolocation, currentItem, 
preferredType, strictType, mqlFilter, mqlOutput;

- (id)initWithStyle:(UITableViewStyle)style {
    if ((self = [super initWithStyle:style])) {
        _search = [[FreebaseSuggestSearch alloc] init];
        _showDetail = YES;
    }
    
    return self;        
}

- (id)init {
    return [self initWithStyle:UITableViewStyleGrouped];
}

- (void)dealloc {
    self.delegate = nil;
    self.search = nil;
    [super dealloc];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    // this allows the search table to appear on top of this view
    _search.view = self.view;
    
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0)];  
    //[self.view addSubview:searchBar];
    self.tableView.tableHeaderView = searchBar;

    _searchController = [[UISearchDisplayController alloc]
                                                   initWithSearchBar:searchBar 
                                                   contentsController:self];
    _searchController.delegate = _search;
    _searchController.searchResultsDataSource = _search;
    _searchController.searchResultsDelegate = _search;
    _searchController.delegate = _search;
    
    NSLog(@"Trying geolocation in %@, = %d", self, self.allowGeolocation);
    if (self.allowGeolocation) {
        searchBar.scopeButtonTitles = 
        [NSArray arrayWithObjects:@"All", @"3km", @"1km", @"0.5km", @"0.25km", nil];        
        searchBar.showsScopeBar = YES;
    } else {
        searchBar.showsScopeBar = NO;
    }
    [searchBar release];
        
    _search.suggestDelegate = self;

    NSLog(@"FreebaseSuggest.viewDidLoad, search = %@", _search);
    
    
    [_itemDetailParentView addSubview:_itemDetail.view];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.itemDetail = [[FreebaseDetail alloc] init];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    
    _search.view = nil;
    [_searchController release];
    _searchController = nil;
}

- (void)cancelClicked
{
    [self.delegate suggest:self itemSelected:nil];    
}

- (void)doneClicked
{
    NSDictionary* item = _search.currentItem;
    if (_newItemType) {
        NSMutableArray* typeList = [NSMutableArray arrayWithObject:
                                    [_newItemType objectForKey:@"id"]];
                                
        for (NSDictionary *type_info in [_newItemType objectForKey:@"/freebase/type_hints/included_types"]) {
            [typeList addObject:[type_info objectForKey:@"id"]];
        }
        item = [NSDictionary dictionaryWithObjectsAndKeys:
                @"unconditional", @"create", 
                [NSNull null], @"id",
                [_search.currentItem objectForKey:@"name"], @"name",
                typeList, @"type",
                nil];
    }
    [self.delegate suggest:self itemSelected:item];
}

- (void)chooseTypeClicked
{
    _typeChooser = [[FreebaseSuggest alloc] init];
    _typeChooser.preferredType = @"/type/type";
    _typeChooser.strictType = YES;
    _typeChooser.allowGeolocation = NO;
    _typeChooser.delegate = self;
    _typeChooser.showDetail = NO;
    _typeChooser.mqlOutput = 
    @"[{\"id\": null, \"name\": null,"
     "  \"/freebase/type_hints/included_types\": [{"
     "     \"id\": null, \"name\": null, \"optional\": true }]"
     "}]";
    
    [self presentModalViewController:_typeChooser animated:YES];
}

- (void)setCurrentItem:(NSDictionary*)currentItem
{
    _search.currentItem = currentItem;
}

- (NSDictionary*)currentItem {
    return _search.currentItem;
}

- (void)setMqlFilter:(NSString*)mqlFilter
{
    _search.mqlFilter = mqlFilter;
}

- (NSString*)mqlFilter
{
    return _search.mqlFilter;
}

- (void)setMqlOutput:(NSString*)mqlOutput
{
    _search.mqlOutput = mqlOutput;
}

- (NSString*)mqlOutput
{
    return _search.mqlOutput;
}

// forwards to searcher
- (BOOL)allowCreateNew {
    return _search.allowCreateNew;
}

- (void)setAllowCreateNew:(BOOL)allowCreateNew {
    _search.allowCreateNew = allowCreateNew;
}

- (BOOL)allowGeolocation {
    return _search.allowGeolocation;
}

- (void)setAllowGeolocation:(BOOL)allowGeolocation {
    _search.allowGeolocation = allowGeolocation;
}

- (NSString*)preferredType {
    return _search.preferredType;
}


- (void)setPreferredType:(NSString*)preferredType
{
    _search.preferredType = preferredType;
}

- (BOOL)strictType {
    return _search.strictType;
}

- (void)setStrictType:(BOOL)strictType
{
    _search.strictType = strictType;
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.searchDisplayController setActive:YES animated:YES];
    NSLog(@"viewDidAppear, appeared = %d", _appearedOnce);
    // a little tricky, hoping that dismissModalViewController is synchronous
    if (!_appearedOnce)
        [self.searchDisplayController.searchBar becomeFirstResponder];
    else
        [self.searchDisplayController setActive:NO animated:NO];
    _appearedOnce = YES;
}

/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
#pragma unused(interfaceOrientation)
    return YES;
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

// this is perhaps a little cheesy - we are the delegate of another FreebaseSuggest
// when we're prompting the user to choose a type

-(void)suggest:(FreebaseSuggest*)suggest itemSelected:(NSDictionary*)itemSelected
{
    if (suggest == _typeChooser) {
        
        _newItemType = [itemSelected retain];
        NSLog(@"Typesuggest complete, got a: %@", itemSelected);
        
        [self dismissModalViewControllerAnimated:YES];
        
        [_typeChooser release];
        _typeChooser = nil;
                
        [self.tableView reloadData];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#pragma unused(tableView)
    return 2;
}

- (void)itemSelected:(NSDictionary*)item
{
    if ([item objectForKey:@"id"]) {
        // real item, has an id - clear out the type information
        [_newItemType release];
        _newItemType = nil;
        _showChooseType = NO;
        
    } else {
        // "create new" style item - show the "Choose type" button
        // 
        if ([self.preferredType isEqualToString:@"/common/topic"])            
            _showChooseType = YES;
        else
            _showChooseType = NO;
    }

    [self.tableView reloadData];
    
    if (_showDetail) {
        [self.itemDetail loadItemDetail: item];
        if (!item || ![item objectForKey:@"id"]) {
            self.itemDetail.articleLabel.text = @"Creating a new topic.";

            NSLog(@"I'd like to assign %@ to %@", _newItemType, self.itemDetail.typeLabel);
            if (_newItemType)
                self.itemDetail.typeLabel.text = [_newItemType objectForKey:@"name"];
        }
        
        // clear out so we can see the detail view
        [self.searchDisplayController setActive:NO animated:YES];
    }
    else
        // jump directly to the user, don't load up detail
        [self doneClicked];

}

#pragma mark Table view methods

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#pragma unused(tableView)
#pragma unused(section)
    
    if (section == 1) {
        // can we show the "Done" button?
        if (self.currentItem)
            return 2;
        else
            return 1;
        
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
#pragma unused(tableView)
    if (indexPath.section == 0)
        return self.itemDetail.view.frame.size.height;

    return self.tableView.rowHeight;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    
    // Set up the cell...
    if (indexPath.section == 0) {
        // detail view
        [cell.contentView addSubview:_itemDetail.view];
        cell.contentView.frame =  _itemDetail.view.frame;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    } else if (indexPath.section == 1) {
        
        // done/cancel buttons - don't show "Done" button if we haven't 
        // chosen a topic yet
        if (indexPath.row == 0 && self.currentItem)  {
            
            if (_showChooseType) {
                cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
                if (_newItemType)
                    cell.textLabel.text = [NSString stringWithFormat:@"Create a %@ named %@",
                                           [_newItemType objectForKey:@"name"],
                                           [self.currentItem objectForKey:@"name"]];
                
                else
                    cell.textLabel.text = @"Choose a type...";
            } else
                cell.textLabel.text = @"Done";

        } else
            cell.textLabel.text = @"Cancel";
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    }
	
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
#pragma unused(tableView)
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            if (_showChooseType) {                
                if (_newItemType)
                    [self doneClicked];
                else
                    [self chooseTypeClicked];
            }
            else 
                [self doneClicked];
            
        }
        else
            [self cancelClicked];
    }
    else if (indexPath.section == 2) {
        // choose type
        [self chooseTypeClicked];
    }
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
}


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

@end

